package com.qiaoba.file.qiniu.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import com.qiaoba.api.file.core.FileCore;
import com.qiaoba.api.file.entity.vo.FileUploadVO;
import com.qiaoba.api.file.util.FileUtil;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云 文件服务实现
 *
 * @author ailanyin
 * @date 2023-09-26 14:36:52
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class QiniuFileServiceImpl implements FileCore {

    @Value("${qiniu.oss.domain}")
    private String domain;

    private final Auth auth;
    private final UploadManager uploadManager;
    private final BucketManager bucketManager;

    @Override
    public FileUploadVO upload(String bucketName, String filename, Long size, InputStream inputStream) {
        try {
            // 设置存储对象名称
            String objectName = DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + UUID.randomUUID().toString() + "." + FileUtil.getExtension(filename);
            // 上传文件
            StringMap putPolicy = new StringMap();
            String upToken = auth.uploadToken(bucketName, null, 3600, putPolicy);
            uploadManager.put(IoUtil.readBytes(inputStream), objectName, upToken);
            FileUploadVO vo = new FileUploadVO();
            vo.setUrl(createUrl(objectName));
            vo.setFileName(filename);
            vo.setPath(objectName);
            return vo;
        } catch (Exception e) {
            log.error("七牛云文件上传失败, 错误信息: {}", e.getMessage());
            throw new ServiceException("七牛云文件上传失败");
        } finally {
            IoUtil.close(inputStream);
        }
    }

    @Override
    public void delete(String bucketName, String path) {
        try {
            bucketManager.delete(bucketName, path);
        } catch (QiniuException e) {
            log.error("七牛云文件删除失败, 错误信息: {}", e.getMessage());
            throw new ServiceException("七牛云文件删除失败");
        }
    }

    private String createUrl(String path) {
        return domain + "/" + path;
    }

}
